import { ACTIVE_MENU_PATH, LOGIN_STATUS, TOKEN, USER_INFO } from '@/global/contance'
import router from '@/router'
import { customRouter } from '@/router/custom-router'
import {
  getHomePageMenu,
  getPersonalInfo,
  registerAccount,
  login,
  updatePassWord,
} from '@/service/common'
import { localCache } from '@/utils/cache'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'

export const useHomePageStore = defineStore('homePage', {
  state: () => ({
    menus: [],
    personalInfo: {},
    userInfo: {},
    token: '',
    isLogin: false,
  }),
  actions: {
    async getHomePageMenu() {
      const paths: RouteRecordRaw[] = []
      const result = await getHomePageMenu()
      if (result.success) {
        const data = result?.data ?? []
        this.menus = data
        data.forEach((item: any) => {
          const cr = customRouter.find((f: any) => f.path === item.url)
          if (cr) {
            paths.push(cr)
          }
        })
        paths.forEach((route) => {
          router.addRoute('main', route)
        })
        const active_path = sessionStorage.getItem(ACTIVE_MENU_PATH)
        router.push(active_path ?? '/share')
      } else {
        ElMessage.error(result?.msg ?? '')
      }
    },
    async getPersonalInfo() {
      const result = await getPersonalInfo('967ab790-82ce-430d-8575-cc7a243d7663')
      if (result.success) {
        this.personalInfo = result.data
        console.log(this.personalInfo, '-----------------------------')
      } else {
        ElMessage.error(result?.msg ?? '')
      }
    },
    async registerAccount(data: any) {
      const result = await registerAccount(data)
      return result
    },
    async login(data: any) {
      const result = await login(data)
      if (result?.success) {
        this.token = result?.token
        this.userInfo = { id: result?.id, account: result?.account }
        //token进行本地缓存
        localCache.setCache(TOKEN, this.token)
        //用户信息缓存
        localCache.setCache(USER_INFO, this.userInfo)
        //更新登录状态
        this.isLogin = true
        localCache.setCache(LOGIN_STATUS, this.isLogin)
      }
      return result
    },
    loadLocalCacheAction() {
      const token = localCache.getCache(TOKEN)
      const userInfo = localCache.getCache(USER_INFO)
      const isLogin = localCache.getCache(LOGIN_STATUS)
      if (token && userInfo) {
        this.token = token
        this.userInfo = userInfo
        this.isLogin = isLogin
      } else {
        this.isLogin = false
        localCache.setCache(LOGIN_STATUS, this.isLogin)
      }
    },
    async updatePassWord(data: any) {
      const result = await updatePassWord({ ...this.userInfo, ...data })
      return result
    },
  },
})
